// 聊天页面WebSocket客户端逻辑
class ChatClient {
    constructor() {
        this.socket = null;
        this.username = null;
        this.isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 3000;
        this.messageHistory = [];
        
        this.init();
    }
    
    init() {
        this.checkUsername();
        this.bindEvents();
        // 只有在用户名存在时才连接WebSocket
        if (this.username) {
            this.connectWebSocket();
        }
    }
    
    checkUsername() {
        this.username = sessionStorage.getItem('chatUsername');
        if (!this.username) {
            this.showUsernameModal();
            return;
        }
        
        // 显示当前用户名
        const currentUsernameElement = document.getElementById('currentUsername');
        if (currentUsernameElement) {
            currentUsernameElement.textContent = this.username;
        }
    }
    
    showUsernameModal() {
        const modal = document.getElementById('usernameModal');
        if (modal) {
            modal.style.display = 'flex';
        }
    }
    
    hideUsernameModal() {
        const modal = document.getElementById('usernameModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }
    
    bindEvents() {
        // 消息发送表单
        const messageForm = document.getElementById('messageForm');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        
        messageForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.sendMessage();
        });
        
        // 输入框事件
        messageInput.addEventListener('input', () => {
            this.autoResizeTextarea();
            this.updateSendButton();
        });
        
        // Ctrl+Enter发送消息
        messageInput.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                this.sendMessage();
            }
        });
        
        // 用户名模态框表单
        const usernameForm = document.getElementById('usernameForm');
        if (usernameForm) {
            usernameForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleUsernameSubmit();
            });
        }
        
        // 页面卸载时断开连接
        window.addEventListener('beforeunload', () => {
            this.disconnect();
        });
        
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                // 页面隐藏时保持连接
            } else {
                // 页面显示时检查连接状态
                if (!this.isConnected) {
                    this.connectWebSocket();
                }
            }
        });
    }
    
    handleUsernameSubmit() {
        const usernameInput = document.getElementById('modalUsername');
        const errorElement = document.getElementById('modalErrorMessage');
        const username = usernameInput.value.trim();
        
        // 验证用户名
        if (!username || username.length < 2 || username.length > 20) {
            this.showModalError('用户名长度应在2-20个字符之间');
            return;
        }
        
        if (!/^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/.test(username)) {
            this.showModalError('用户名只能包含中文、英文、数字、下划线和连字符');
            return;
        }
        
        // 保存用户名
        this.username = username;
        sessionStorage.setItem('chatUsername', username);
        
        // 更新显示
        const currentUsernameElement = document.getElementById('currentUsername');
        if (currentUsernameElement) {
            currentUsernameElement.textContent = username;
        }
        
        // 隐藏模态框
        this.hideUsernameModal();
        
        // 连接WebSocket
        this.connectWebSocket();
    }
    
    showModalError(message) {
        const errorElement = document.getElementById('modalErrorMessage');
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }
    }
    
    connectWebSocket() {
        if (!this.username) {
            console.warn('用户名未设置，无法连接WebSocket');
            return;
        }
        
        try {
            // 构建SockJS URL
            const protocol = window.location.protocol === 'https:' ? 'https:' : 'http:';
            const host = window.location.host;
            const sockjsUrl = `${protocol}//${host}/chat`;
            
            console.log('连接SockJS:', sockjsUrl);
            this.updateConnectionStatus('connecting');
            
            // 使用SockJS连接以提高兼容性
            this.socket = new SockJS(sockjsUrl);
            
            this.socket.onopen = () => {
                console.log('SockJS连接已建立');
                this.isConnected = true;
                this.reconnectAttempts = 0;
                this.updateConnectionStatus('connected');
                
                // 发送加入消息
                this.sendJoinMessage();
            };
            
            this.socket.onmessage = (event) => {
                try {
                    const message = JSON.parse(event.data);
                    this.handleMessage(message);
                } catch (error) {
                    console.error('解析消息失败:', error, event.data);
                }
            };
            
            this.socket.onclose = (event) => {
                console.log('SockJS连接已关闭:', event.code, event.reason);
                this.isConnected = false;
                this.updateConnectionStatus('disconnected');
                
                // 自动重连
                if (event.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) {
                    this.scheduleReconnect();
                }
            };
            
            this.socket.onerror = (error) => {
                console.error('SockJS错误:', error);
                this.updateConnectionStatus('error');
            };
            
        } catch (error) {
            console.error('创建SockJS连接失败:', error);
            this.updateConnectionStatus('error');
        }
    }
    
    scheduleReconnect() {
        this.reconnectAttempts++;
        const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
        
        console.log(`${delay/1000}秒后尝试第${this.reconnectAttempts}次重连...`);
        this.updateConnectionStatus('reconnecting', this.reconnectAttempts);
        
        setTimeout(() => {
            if (!this.isConnected) {
                this.connectWebSocket();
            }
        }, delay);
    }
    
    sendJoinMessage() {
        const joinMessage = {
            type: 'JOIN',
            username: this.username,
            timestamp: new Date().toISOString()
        };
        
        this.sendWebSocketMessage(joinMessage);
    }
    
    sendMessage() {
        const messageInput = document.getElementById('messageInput');
        const content = messageInput.value.trim();
        
        if (!content || !this.isConnected) {
            return;
        }
        
        const message = {
            type: 'CHAT',
            username: this.username,
            message: content,
            timestamp: new Date().toISOString()
        };
        
        this.sendWebSocketMessage(message);
        messageInput.value = '';
        this.autoResizeTextarea();
        this.updateSendButton();
    }
    
    sendWebSocketMessage(message) {
        if (this.socket && this.socket.readyState === SockJS.OPEN) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.warn('SockJS未连接，无法发送消息');
        }
    }
    
    handleMessage(message) {
        console.log('收到消息:', message);
        
        switch (message.type) {
            case 'CHAT':
                this.displayChatMessage(message);
                break;
            case 'JOIN':
                this.displaySystemMessage(`${message.username} 加入了聊天室`);
                break;
            case 'LEAVE':
                this.displaySystemMessage(`${message.username} 离开了聊天室`);
                break;
            case 'USER_LIST':
                this.updateUserList(message.users);
                break;
            case 'ERROR':
                this.displayErrorMessage(message.message);
                break;
            default:
                console.warn('未知消息类型:', message.type);
        }
        
        // 保存到历史记录
        this.messageHistory.push(message);
        if (this.messageHistory.length > 100) {
            this.messageHistory.shift();
        }
    }
    
    displayChatMessage(message) {
        const messagesContainer = document.getElementById('messagesContainer');
        const messageElement = document.createElement('div');
        messageElement.className = `message ${message.username === this.username ? 'own' : 'other'}`;
        
        const time = new Date(message.timestamp).toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
        
        messageElement.innerHTML = `
            <div class="message-bubble">
                <div class="message-header">
                    <span class="username">${this.escapeHtml(message.username)}</span>
                    <span class="timestamp">${time}</span>
                </div>
                <div class="message-content">${this.escapeHtml(message.message)}</div>
            </div>
        `;
        
        messagesContainer.appendChild(messageElement);
        this.scrollToBottom();
    }
    
    displaySystemMessage(content) {
        const messagesContainer = document.getElementById('messagesContainer');
        const messageElement = document.createElement('div');
        messageElement.className = 'message system';
        
        messageElement.innerHTML = `
            <div class="message-bubble">
                <div class="message-content">${this.escapeHtml(content)}</div>
            </div>
        `;
        
        messagesContainer.appendChild(messageElement);
        this.scrollToBottom();
    }
    
    displayErrorMessage(content) {
        const messagesContainer = document.getElementById('messagesContainer');
        const messageElement = document.createElement('div');
        messageElement.className = 'message error';
        
        messageElement.innerHTML = `
            <div class="message-bubble">
                <div class="message-content">❌ ${this.escapeHtml(content)}</div>
            </div>
        `;
        
        messagesContainer.appendChild(messageElement);
        this.scrollToBottom();
    }
    
    updateUserList(users) {
        const userListContainer = document.getElementById('userListContainer');
        const userCountElement = document.getElementById('userCount');
        
        if (userCountElement) {
            userCountElement.textContent = users.length;
        }
        
        if (userListContainer) {
            userListContainer.innerHTML = '';
            
            users.forEach(user => {
                const userElement = document.createElement('div');
                userElement.className = `user-item ${user === this.username ? 'current-user' : ''}`;
                userElement.innerHTML = `
                    <div class="user-avatar">👤</div>
                    <div class="user-name">${this.escapeHtml(user)}</div>
                    ${user === this.username ? '<div class="user-badge">我</div>' : ''}
                `;
                userListContainer.appendChild(userElement);
            });
        }
    }
    
    updateConnectionStatus(status, attempt = 0) {
        const statusElement = document.getElementById('connectionStatus');
        const onlineStatusElement = document.getElementById('onlineStatus');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        
        let statusText = '';
        let statusClass = '';
        
        switch (status) {
            case 'connecting':
                statusText = '连接中...';
                statusClass = 'connecting';
                break;
            case 'connected':
                statusText = '已连接';
                statusClass = 'connected';
                break;
            case 'disconnected':
                statusText = '连接断开';
                statusClass = 'disconnected';
                break;
            case 'reconnecting':
                statusText = `重连中... (${attempt}/${this.maxReconnectAttempts})`;
                statusClass = 'reconnecting';
                break;
            case 'error':
                statusText = '连接错误';
                statusClass = 'error';
                break;
        }
        
        if (statusElement) {
            statusElement.textContent = statusText;
            statusElement.className = `connection-status ${statusClass}`;
            
            // 连接成功后隐藏状态指示器
            if (status === 'connected') {
                setTimeout(() => {
                    statusElement.style.display = 'none';
                }, 2000);
            } else {
                statusElement.style.display = 'block';
            }
        }
        
        if (onlineStatusElement) {
            onlineStatusElement.textContent = statusText;
        }
        
        // 更新输入框状态
        const isConnected = status === 'connected';
        if (messageInput) {
            messageInput.disabled = !isConnected;
            messageInput.placeholder = isConnected ? '输入消息...' : '连接中，请稍候...';
        }
        
        if (sendBtn) {
            sendBtn.disabled = !isConnected;
        }
    }
    
    updateSendButton() {
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        
        if (messageInput && sendBtn) {
            const hasContent = messageInput.value.trim().length > 0;
            sendBtn.disabled = !hasContent || !this.isConnected;
        }
    }
    
    autoResizeTextarea() {
        const messageInput = document.getElementById('messageInput');
        if (messageInput) {
            messageInput.style.height = 'auto';
            messageInput.style.height = Math.min(messageInput.scrollHeight, 120) + 'px';
        }
    }
    
    scrollToBottom() {
        const messagesContainer = document.getElementById('messagesContainer');
        if (messagesContainer) {
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
    }
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    disconnect() {
        if (this.socket) {
            // 发送离开消息
            const leaveMessage = {
                type: 'LEAVE',
                username: this.username,
                timestamp: new Date().toISOString()
            };
            
            this.sendWebSocketMessage(leaveMessage);
            
            // 关闭连接
            this.socket.close(1000, '用户主动离开');
            this.socket = null;
        }
        
        this.isConnected = false;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.chatClient = new ChatClient();
});